package com.example.thread;



public class WaitAndNotifyTest {
    public static void main(String[] args){
        Object obj = new Object();
        Object obj1 = new Object();
        MyThread t = new WaitAndNotifyTest.MyThread("hello",obj);
        MyThread1 t2 = new WaitAndNotifyTest.MyThread1("world",obj);
        Thread t1 = new Thread(t);
        Thread t3 = new Thread(t2);
        t1.start();
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        t3.start();
    }

     static class MyThread implements Runnable{
        private String message;
        private Object obj;

        MyThread(String message,Object obj){
            this.message = message;
            this.obj = obj;
        }

        private  void synchMethod(){

            synchronized(obj){
                System.out.println(Thread.interrupted());
                try {
                        System.out.println(Thread.currentThread().getName()+"waiting");
                        obj.wait();
                    Thread.sleep(4000);
                    System.out.println(Thread.currentThread().getName()+"wake up");
                } catch (InterruptedException e) {
                    System.out.println(Thread.interrupted());
                    e.printStackTrace();
                }
                System.out.println(this.message);
            }
        }


        public void run(){
            System.out.println("in run..." + Thread.currentThread().getName());
            synchMethod();

        }
    }

    static class MyThread1 implements Runnable{
        private String message;
        private Object obj;

        MyThread1(String message,Object obj){
            this.message = message;
            this.obj = obj;
        }

        private  void synchMethod(){
            synchronized(obj){
                System.out.println(Thread.currentThread().getName()+"notify");
                obj.notify();
                System.out.println(this.message);
            }
        }

        private  void synchMethodInterapte(){
            synchronized(obj){
                System.out.println(Thread.currentThread().getName()+"synchMethodInterapte");
                Thread.yield();
                System.out.println(this.message);
            }
        }


        public void run(){
            System.out.println("in run..." + Thread.currentThread().getName());
            synchMethod();

        }
    }
}
